﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net.Security;
using System.IO;
using Hardanger.Model;

namespace Hardanger.Features
{
    public class TCPWebClient
    {
        static public TCPWebResponse Process(TCPWebRequest request, int timeout = 3000)
        {
            if (timeout <= 0)
                timeout = 3000;
              
            TCPWebResponse response = new TCPWebResponse();
            TcpClient client = new TcpClient(request.Hostname,request.Port);
            NetworkStream rawStream = client.GetStream();
            Stream commStream;
            if (request.SSL)
            {
                SslStream sslStream = new SslStream(
                    rawStream,
                    false,
                    null,
                    null
                    );
				sslStream.AuthenticateAsClient(request.Hostname);
                commStream = sslStream;
            }
            else
            {
                commStream = rawStream;
            }
            commStream.ReadTimeout = commStream.WriteTimeout = timeout;
            byte[] requestBytes = Encoding.UTF8.GetBytes(request.Raw);
            commStream.Write(requestBytes,0,requestBytes.Length);            
            commStream.Flush();
            response.Raw = ReadMessage(commStream);
			if (String.IsNullOrEmpty(response.Raw))
			{
				throw new HardangerException("Remote Server returned empty response");
			}
            return response;
        }

        static private string ReadMessage(Stream stream)
        {
            byte[] buffer = new byte[2048];
            StringBuilder messageData = new StringBuilder();
            int bytes = -1;
            do
            {
                bytes = stream.Read(buffer, 0, buffer.Length);

                // Use Decoder class to convert from bytes to UTF8
                // in case a character spans two buffers.
                Decoder decoder = Encoding.UTF8.GetDecoder();
                char[] chars = new char[decoder.GetCharCount(buffer, 0, bytes)];
                decoder.GetChars(buffer, 0, bytes, chars, 0);
                messageData.Append(chars);
            } while (bytes != 0);

            return messageData.ToString();
        }
    }
}
